﻿using BCCommon;
using BCCommon.Enums;
using BCData.TMS.WorkingCompany;
using BCDto.TMS.WorkingCompany;
using BCEntity.TMS.WorkingCompany;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BCData.Sim.Company.Company;
using BCData.Sim.Company.Department;
using BCDto.Sim.Admin.Admin;

namespace BCService.TMS.WorkingCompany
{
	public class WorkingCompanyService : IWorkingCompanyService
	{
		private readonly IDatabaseContext databaseContext;
		private readonly IApplicationContextService applicationContextService;
		private readonly IRedisService redisService;
		private readonly IWorkingCompanyData workingCompanyData;
		private readonly ICompanyData companyData;
		private readonly IDepartmentData departmentData;
		private readonly string key = string.Format("{0}", EntityNameConst.WorkingCompanyEntity);

        public WorkingCompanyService(IDatabaseContext databaseContext,
            IApplicationContextService applicationContextService,
            IRedisService redisService,
            IWorkingCompanyData workingCompanyData,
            ICompanyData companyData, 
			IDepartmentData departmentData)
        {
            this.databaseContext = databaseContext;
            this.applicationContextService = applicationContextService;
            this.redisService = redisService;
            this.workingCompanyData = workingCompanyData;
            this.companyData = companyData;
            this.departmentData = departmentData;
        }

        #region 检查劳务公司是否存在
        public bool Exists(long workingCompanyId)
		{
			return this.workingCompanyData.Exists(workingCompanyId).GetAwaiter().GetResult();
		}
		#endregion

		#region 添加劳务公司
		public WorkingCompanyDto Add(WorkingCompanyRequestDto requestDto,AdminDto admin)
		{ 
			var departmentEnitiy = departmentData.GetById(requestDto.DepartmentId).GetAwaiter().GetResult() ?? throw new ArgumentException("部门Id不存在!");
			if (departmentEnitiy.CompanyId != admin.CompanyId) throw new ArgumentException("部门Id错误,不属于本公司!");
			var list = workingCompanyData.GetOnlyList(admin.CompanyId, null, requestDto.WorkingCompanyName).GetAwaiter().GetResult();
			if(list!=null && list.Count()>0)
            {
				if (list.Count(s => s.WorkingCompanyName == requestDto.WorkingCompanyName) > 0)
					throw new ArgumentException("劳务公司名称重复!");
            }
			var entity = requestDto.As<WorkingCompanyEntity>();
			entity.CompanyId = admin.CompanyId;
			entity.CompanyName = admin.CompanyName;
			entity.DepartmentName = departmentEnitiy.DepartmentName;

			entity.CreateAdminName = admin.FullName;
			entity.CreateAdminId = admin.AdminId;

			return this.workingCompanyData.Add(entity).GetAwaiter().GetResult().As<WorkingCompanyDto>();
		}
		#endregion

		#region 修改劳务公司
		public WorkingCompanyDto Update(WorkingCompanyPutDto putDto,AdminDto admin)
		{
			var org = workingCompanyData.GetEntity(putDto.WorkingCompanyId).GetAwaiter().GetResult()?? throw new ArgumentException("此记录不存在!");
			
			var departmentEnitiy = departmentData.GetById(putDto.DepartmentId).GetAwaiter().GetResult()?? throw new ArgumentException("部门Id不存在!");
            if (departmentEnitiy.CompanyId != admin.CompanyId) throw new ArgumentException("部门Id错误,不属于公司!");

            var list = workingCompanyData.GetOnlyList(admin.CompanyId, null, putDto.WorkingCompanyName).GetAwaiter().GetResult();
            if (list != null && list.Count() > 0)
            {
                foreach (var item in list)
                {
					if(item.WorkingCompanyId != putDto.WorkingCompanyId)
                        throw new ArgumentException("劳务公司名称重复!");
                }
            }

            var entity = putDto.As<WorkingCompanyEntity>();
			entity.DepartmentName = departmentEnitiy.DepartmentName;
			entity.EnabledManualAssign = org.EnabledManualAssign;

			if(putDto.ManualAssignWaitTime.HasValue)
            {
				entity.ManualAssignWaitTime = putDto.ManualAssignWaitTime.Value;
            }
			else
            {
				entity.ManualAssignWaitTime = org.ManualAssignWaitTime;
            }


			entity.EditAdminName = admin.FullName;
			entity.EditAdminId = admin.AdminId;
            entity.UpdateTime = DateTime.Now;
            var result = this.workingCompanyData.Update(entity).GetAwaiter().GetResult().As<WorkingCompanyDto>();
			string cacheKey = this.redisService.GetKey(key, entity.WorkingCompanyId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
        #endregion

        #region 启用禁用手动指派
        public void  EnabledManualAssign(long workingCompanyId,bool isEnable, AdminDto admin)
        {
			var entity = workingCompanyData.GetEntity(workingCompanyId).GetAwaiter().GetResult()?? throw new ArgumentException("此记录不存在!");
			entity.EnabledManualAssign = isEnable;
            entity.EditAdminName = admin.FullName;
            entity.EditAdminId = admin.AdminId;
			entity.UpdateTime = DateTime.Now;
            var result = this.workingCompanyData.Update(entity).GetAwaiter().GetResult().As<WorkingCompanyDto>();
            string cacheKey = this.redisService.GetKey(key, workingCompanyId);
            this.redisService.DeleteAsync(cacheKey);

        }
		#endregion

        #region 删除劳务公司
        public bool Delete(long workingCompanyId)
		{
			if (!this.Exists(workingCompanyId))
			{
				throw new ArgumentException("此记录不存在!");
			}

			var result = this.workingCompanyData.Delete(workingCompanyId).GetAwaiter().GetResult();
			string cacheKey = this.redisService.GetKey(key, workingCompanyId);
			this.redisService.DeleteAsync(cacheKey);
			return result;
		}
		#endregion

		#region 获取劳务公司
		public WorkingCompanyDto Get(long workingCompanyId)
		{
			string cacheKey = this.redisService.GetKey(key, workingCompanyId);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.workingCompanyData.GetEntity(workingCompanyId).GetAwaiter().GetResult();
				return data;
			}, TimeSpan.FromDays(1));
			return result.As<WorkingCompanyDto>();
		}
		#endregion

		#region 获取劳务公司列表
		public IEnumerable<WorkingCompanyDto> GetOnlyList(AdminDto admin, long? departmentId, string workingCompanyName)
		{
			var result = this.redisService.TryGet(key, () =>
			{
				return this.workingCompanyData.GetOnlyList(admin.CompanyId, departmentId, workingCompanyName).GetAwaiter().GetResult();
			}, TimeSpan.FromDays(1));
			return result.As<IEnumerable<WorkingCompanyDto>>();
		}
		#endregion

		#region 获取劳务公司列表

		public IEnumerable<WorkingCompanyDto> GetListByCountyCode(string countyCode)
		{
			string cacheKey = this.redisService.GetKey(key,countyCode);
			var result = this.redisService.TryGet(key, () =>
			{
				return this.workingCompanyData.GetListByCountyCode(countyCode).GetAwaiter().GetResult();
			}, TimeSpan.FromDays(1));
			return result.As<IEnumerable<WorkingCompanyDto>>();
		}
		#endregion

		#region 获取劳务公司分页
		public PageableList<WorkingCompanyDto> Query(AdminDto admin,long? departmentId,string workingCompanyName,DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
		{
			string cacheKey = this.redisService.GetKey(key, start, end, sortName, ascending, pageIndex, pageSize);
			var result = this.redisService.TryGet(cacheKey, () =>
			{
				var data = this.workingCompanyData.Query(admin.CompanyId,departmentId,workingCompanyName,start, end, sortName, ascending, pageIndex, pageSize).GetAwaiter().GetResult();
				return new PageableList<WorkingCompanyDto>
				{
					Count = data.Item2,
					Items = data.Item1.As<IEnumerable<WorkingCompanyDto>>(),
					PageIndex = pageIndex,
					PageSize = pageSize,
					ServerTime = DateTime.Now
				};
			}, TimeSpan.FromMinutes(30));

			return result;
		}

        #endregion

    }
}